<?php

namespace app\sys\controller;

use Exception;
use Psr\Log\NullLogger;
use think\admin\Controller;
use think\admin\model\SysQueue;
use think\admin\service\AdminService;
use think\admin\service\QueueService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\HttpResponseException;

/**
 * 系统任务管理
 * @class Queue
 * @package app\sys\controller
 */
class Queue extends Controller
{
    /**
     * 系统任务管理
     * @auth true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function page()
    {
        $query = SysQueue::mQuery();
        $query->equal('status')->like('code|title#title,command');
        $query->timeBetween('enter_time,exec_time')->dateBetween('create_time');
        $lists = $query->order('id ASC')->page();
    }

    /**
     * 重启系统任务
     * @auth true
     */
    public function redo()
    {
        try {
            $data = $this->_vali(['code.require' => '任务编号不能为空！']);
            $queue = QueueService::instance()->initialize($data['code'])->reset();
            $queue->progress(1, '>>> 任务重置成功 <<<', 0.00);
            $this->success('任务重置成功！', $queue->code);
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (Exception $exception) {
            trace_file($exception);
            $this->error($exception->getMessage());
        }
    }

    /**
     * 查询任务进度
     * @login true
     * @throws \think\admin\Exception
     */
    public function progress()
    {
        $input = $this->_vali(['code.require' => '任务编号不能为空！']);
        $this->app->db->setLog(new NullLogger()); /* 关闭数据库请求日志 */
        $message = SysQueue::mk()->where($input)->value('message', '');
        $this->success('获取任务进度成功！', json_decode($message, true));
    }
    /**
     * 清理运行数据
     * @auth true
     */
    public function clear()
    {
        $this->_queue('定时清理系统运行数据', "xadmin:queue clean", 0, [], 0, 3600);
    }

    /**
     * 删除系统任务
     * @auth true
     */
    public function delete()
    {
        SysQueue::mDelete();
    }

    /**
     * 停止监听服务
     * @auth true
     */
    public function stop()
    {
        if (AdminService::isSuper() || AdminService::isGlobalAdmin()) try {
            $message = $this->app->console->call('xadmin:queue', ['stop'])->fetch();
            $msg = !empty($message) ? explode('#', $message)[1] : '';
            if (stripos($message, 'sent end signal to process')) {
                sysoplog('系统运维管理', '尝试停止任务监听服务');
                $this->success('停止任务监听服务成功！', ['status' => false, 'msg' => $msg]);
            } elseif (stripos($message, 'processes to stop')) {
                $this->success('没有找到需要停止的服务！', ['status' => false, 'msg' => $msg]);
            } else {
                $this->error(nl2br($message), ['status' => true, 'msg' => $msg]);
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (Exception $exception) {
            trace_file($exception);
            $this->error($exception->getMessage());
        } else {
            $this->error('请使用超管账号操作！');
        }
    }

    /**
     * 启动监听服务
     * @auth true
     */
    public function start()
    {
        if (AdminService::isSuper() || AdminService::isGlobalAdmin()) try {
            $message = $this->app->console->call('xadmin:queue', ['start'])->fetch();
            $msg = !empty($message) ? explode('#', $message)[1] : '';
            if (stripos($message, 'daemons started successfully for pid')) {
                sysoplog('系统运维管理', '尝试启动任务监听服务');
                $this->success('任务监听服务启动成功！', ['status' => true, 'msg' => $msg]);
            } elseif (stripos($message, 'daemons already exist for pid')) {
                $this->success('任务监听服务已经启动！', ['status' => true, 'msg' => $msg]);
            } else {
                $this->error(nl2br($message), ['status' => false, 'msg' => $msg]);
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (Exception $exception) {
            trace_file($exception);
            $this->error($exception->getMessage());
        } else {
            $this->error('请使用超管账号操作！');
        }
    }

    /**
     * 检查监听服务
     * @auth true
     */
    public function status()
    {
        if (AdminService::isSuper() || AdminService::isGlobalAdmin()) try {
            $message = $this->app->console->call('xadmin:queue', ['status'])->fetch();
            if (preg_match('/process.*?\d+.*?running/', $message)) {
                $this->success('任务监听服务已启动！', ['status' => true, 'msg' => $message]);
            } else {
                $this->success('任务监听服务未启动！', ['status' => false, 'msg' => $message]);
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (Exception $exception) {
            trace_file($exception);
            $this->error($exception->getMessage());
        } else {
            $this->error('任务监听服务无权限！', ['status' => false, 'msg' => '只有超级管理员才能操作']);
        }
    }

    /**
     * 分页数据回调处理
     * @param array $data
     * @param array $result
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function _page_page_filter(array $data, array &$result)
    {
        $result['extra'] = ['dos' => 0, 'pre' => 0, 'oks' => 0, 'ers' => 0];
        SysQueue::mk()->field('status,count(1) count')->group('status')->select()->map(function ($item) use (&$result) {
            if (intval($item['status']) === 1) $result['extra']['pre'] = $item['count'];
            if (intval($item['status']) === 2) $result['extra']['dos'] = $item['count'];
            if (intval($item['status']) === 3) $result['extra']['oks'] = $item['count'];
            if (intval($item['status']) === 4) $result['extra']['ers'] = $item['count'];
        });
    }
}
